//index.js
//获取应用实例
var httpRequest = require('../../utils/httpRequest');
var utils = require('../../utils/util.js');
const app = getApp()
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;
var drawFlag = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;

Page({
  data: {
    projectNo: '',
    projectInfo: '',  // 项目基本信息
    userInfo: '',
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function (options) {
    this.setData({
      projectNo: decodeURIComponent(options.scene)
    })
    this.getProjectInfo(this.data.projectNo)
    this.popup = this.selectComponent("#popup");
    this.popup.showPopup();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      this.popup.hidePopup();
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        console.log(res.userInfo)
        this.popup.hidePopup();
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.popup.hidePopup();
        }
      })
    }
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth;//设备宽度
        canvash = res.windowHeight
      }
    });
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  onShow: function (e) {
  },
  //完成,保存图片，并上传到服务器
  getimg:function() {
    if(drawFlag == false){
      wx.showToast({
        title: '请签名！', 
        icon: 'none',   
        duration: 1500   // 提示窗停留时间，默认1500ms
    })
      return
    }

    var that = this;
    //绘制图片
    const ctx = wx.createCanvasContext('canvas')
    ctx.setFillStyle('#FFFFFF')
    ctx.setStrokeStyle("red")
    ctx.draw(true, setTimeout(function () {
    wx.canvasToTempFilePath({
     canvasId: 'canvas',
     success: function (res) {
      wx.getFileSystemManager().readFile({
        filePath: res.tempFilePath,  //图片路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          var imageStr = 'data:image/jpeg;base64,' + res.data;
          console.log(imageStr)
          that.setData({
            sigImage: imageStr
          })   
            httpRequest.requestUrl({
              url: "dop/archives/update/" ,
              method: "post",
              params: {
                nickName: that.data.userInfo.nickName,
                avatarUrl: that.data.userInfo.avatarUrl,
                projectNo: that.data.projectNo,
                sigImage: that.data.sigImage,
                projectName:that.data.projectInfo.projectName,
                projectAuthorize:that.data.projectInfo.projectAuthorize
              },
            }).then(data => {
              if(data && data.code === 0){   
                that.getProjectInfo(that.data.projectNo)
                wx.showToast({
                  title: '提交成功！', 
                  icon: 'success',   
                  duration: 1500   // 提示窗停留时间，默认1500ms
                })
                 resolve(data)
              }else{
                wx.showToast({
                  title: '提交出错！', 
                  icon: 'warn',   
                  duration: 1500   // 提示窗停留时间，默认1500ms
              })
                reject(data)
              }
            })
        }
      })

    }
    })
    }, 100))
    },
   //取消事件
   _error() {
    utils.TipModel('错误','拒绝授权，将无法获取签字权！', 0);
  },
  //确认事件
  _success() {
    if(app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
      this.popup.hidePopup();
      wx.showToast({
        title: '授权成功！',
        icon: 'success',
        duration: 2000//持续的时间
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 通过项目编号获取项目信息
   * @param {项目编号} projectNo 
   */
  getProjectInfo(projectNo) {
    let that = this
    return new Promise((resolve, reject) => {
      httpRequest.requestUrl({
        url: "dop/archives/info/" ,
        method: "get",
        params:{ 'projectNo': projectNo }
      }).then(data => {
        if(data && data.code === 0){
          that.setData({
            projectInfo: data.archives  
          });
          resolve(data)
        }else{
          wx.showLoading({
            title: '出错',
          });
          reject(data)
        }
      })
    })
  },
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  //开始
  canvasStart: function (event) {
    drawFlag = true;
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
    //context.moveTo(event.changedTouches[0].x, event.changedTouches[0].y);

  },
//过程
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };
    context.clearRect(0, 0, canvasw, canvash);
    context.setFillStyle('#FFFFFF')
    context.setStrokeStyle("red")
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  cleardraw: function () {
    drawFlag = false;
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
})
